package com.csv.controller;

import com.csv.pojo.Country;

import com.csv.pojo.Result;
import com.csv.service.CountryService;
import com.csv.util.ExportUtil;
import com.csv.util.ResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName DownloadFileController
 * @Description TODO
 * @Author zhangshuai
 * @Date 2019/4/22 23:08
 * @Version 1.0
 **/
@RestController
@RequestMapping("/test")
@Slf4j
public class DownloadFileController {
/*
    @Autowired
    private SysLogService sysLogService;*/

    @Autowired
    private CountryService countryService;

    @GetMapping("/file")
    public Result download(HttpServletResponse response) {
        List<Map<String, Object>> dataList = null;

        List<Country> logList = countryService.findAll();// 查询到要导出的信息

        if (logList.size() == 0) {
            ResultUtil.failure("无数据导出");
        }
        String sTitle = "id,用户名,操作类型,操作方法,创建时间";
        String fName = "log_";
        String mapKey = "getCountryId,getCountryName,getCountryUrl,getMarketplace,getCapital";
        dataList = new ArrayList<>();
        Map<String, Object> map = null;
        for (Country order : logList) {
            map = new HashMap<>();

            map.put("getCountryId", order.getCountryId());
            map.put("getCountryName", order.getCountryName());
            map.put("getCountryUrl", order.getCountryUrl());
            map.put("getMarketplace", order.getMarketplace());
            map.put("getCapital", order.getCapital());

            dataList.add(map);
        }
        try (final OutputStream os = response.getOutputStream()) {
            ExportUtil.responseSetProperties(fName, response);
            ExportUtil.doExport(dataList, sTitle, mapKey, os);
            return null;
        } catch (Exception e) {
            log.error("生成csv文件失败", e);
        }
        return ResultUtil.failure("数据导出出错");
    }
}

